const transTree = (data) => {
    let result = []
    let map = {}
    if (!Array.isArray(data)) {//验证data是不是数组类型
        return []
    }
    data.forEach(item => {//建立每个数组元素id和该对象的关系
        map[item.id] = item //这里可以理解为浅拷贝，共享引用
    })
    data.forEach(item => {
        let parent = map[item.parentId] //找到data中每一项item的爸爸
        if (parent) {//说明元素有爸爸，把元素放在爸爸的children下面
            (parent.children || (parent.children = [])).push(item)
        } else {//说明元素没有爸爸，是根节点，把节点push到最终结果中
            result.push(item) //item是对象的引用
        }
    })
    return result //数组里的对象和data是共享的
}

export const RefreshRoutes = (vm, roleid) => {
    return new Promise((resolve, reject) => {
        vm.$store.dispatch("route/PromiseRoute", roleid).then((routes) => {
            // console.log(roleid);
            // console.log(routes);

            // 将routes array 转为 tree
            const res = transTree(routes)
            // console.log(res)

            res.forEach(p => {
                vm.$router.addRoute("Layout", {
                    path: p.path.slice(1),
                    name: p.meta.name,
                    meta: {title: p.meta.title, disabled: true},
                    component: () => import("@/views" + p.path),
                })
                "children" in p && p.children.forEach(c => {
                    vm.$router.addRoute(p.meta.name, {
                        path: p.path + c.path,
                        name: c.meta.name,
                        meta: {title: c.meta.title, disabled: false},
                        component: () => import("@/views" + p.path + c.path),
                    })
                })
            })

            // routes.forEach((m) => {
            //     vm.$router.addRoute("Layout", {
            //         path: m.path.slice(1),
            //         name: m.meta.name,
            //         meta: {title: m.meta.title},
            //         component: () => import("@/views/" + m.component),
            //     });
            // });
            // console.log(vm.$router.getRoutes());
        });
        resolve()
        // vm.$router.onReady(() => {resolve()} )
    })
};